package com.lhn.case1;

import org.apache.zookeeper.*;
import org.apache.zookeeper.client.ZKClientConfig;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

/**
 * 〈一句话功能简述>
 * 〈〉
 *
 * @Author 17505
 * @Create 2022/3/11
 * @Since 1.0.0
 */
public class DistributeClient {

    private String connectString = "192.168.3.33:2181";
    private int timeout = 2000;
    private ZooKeeper zooKeeper;


    public static void main(String[] args) throws IOException, KeeperException, InterruptedException {
        DistributeClient client = new DistributeClient();
        // 1.获取 zk 连接
        client.getConnect();

        // 2 监听
        client.getServerList();

        // 3 启动业务逻辑（睡觉）
        client.business();
    }

    private void getServerList() throws KeeperException, InterruptedException {
        List <String> children = zooKeeper.getChildren("/servers", true);
        ArrayList <String> servers = new ArrayList <>();
        for (String child : children) {
            byte[] data = zooKeeper.getData("/servers/" + child, false, null);
            servers.add(new String(data));
        }
        System.out.println(servers);
    }

    private void business() {
        try {
            Thread.sleep(Long.MAX_VALUE);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void getConnect() throws IOException {
        ZKClientConfig config = new ZKClientConfig();
        config.setProperty(ZKClientConfig.ENABLE_CLIENT_SASL_KEY, "false");
        zooKeeper = new ZooKeeper(connectString, timeout, new Watcher() {
            @Override
            public void process(WatchedEvent event) {
                try {
                    getServerList();
                } catch (KeeperException e) {
                    e.printStackTrace();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }, config);
    }

}